package io.github.talelin.latticy.common.listener;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.github.talelin.autoconfigure.bean.MetaInfo;
import io.github.talelin.autoconfigure.bean.PermissionMetaCollector;
import io.github.talelin.latticy.common.enumeration.GroupLevelEnum;
import io.github.talelin.latticy.common.pojo.GroupConfigEntity;
import io.github.talelin.latticy.common.util.EnumUtils;
import io.github.talelin.latticy.model.GroupDO;
import io.github.talelin.latticy.model.GroupPermissionDO;
import io.github.talelin.latticy.model.PermissionDO;
import io.github.talelin.latticy.service.GroupPermissionService;
import io.github.talelin.latticy.service.GroupService;
import io.github.talelin.latticy.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author pedro@TaleLin
 * @author colorful@TaleLin
 */
@Component
public class PermissionHandleListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private PermissionMetaCollector metaCollector;

    @Autowired
    private GroupService groupService;

    @Autowired
    private GroupPermissionService groupPermissionService;

    @Autowired
    private GroupConfigEntity groupEntity;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        addNewPermissions();
        removeUnusedPermissions();
        createSysGroup();
//        createAdminGroupPermission();
    }

    private void addNewPermissions() {
        metaCollector.getMetaMap().values().forEach(meta -> {
            String module = meta.getModule();
            String permission = meta.getPermission();
            createPermissionIfNotExist(permission, module);
        });
    }

    private void removeUnusedPermissions() {
        List<PermissionDO> allPermissions = permissionService.list();
        Map<String, MetaInfo> metaMap = metaCollector.getMetaMap();
        for (PermissionDO permission : allPermissions) {
            boolean stayedInMeta = metaMap
                    .values()
                    .stream()
                    .anyMatch(meta -> meta.getModule().equals(permission.getModule())
                            && meta.getPermission().equals(permission.getName()));
            if (!stayedInMeta) {
                permission.setMount(false);
                permissionService.updateById(permission);
            }
        }
    }

    private void createPermissionIfNotExist(String name, String module) {
        QueryWrapper<PermissionDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(PermissionDO::getName, name).eq(PermissionDO::getModule, module);
        PermissionDO permission = permissionService.getOne(wrapper);
        if (permission == null) {
            permissionService.save(PermissionDO.builder().module(module).name(name).build());
        }
        if (permission != null && !permission.getMount()) {
            permission.setMount(true);
            permissionService.updateById(permission);
        }
    }

    private void createSysGroup() {
        List<String> names = groupEntity.getNames();
        List<String> infos = groupEntity.getInfos();
        List<Integer> levels = groupEntity.getLevels();
        QueryWrapper<GroupDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(GroupDO::getName, names);
        List<GroupDO> defaultGroupList = groupService.getBaseMapper().selectList(wrapper);
        List<GroupDO> sysGroupList = new ArrayList<>();
        if (CollUtil.isEmpty(defaultGroupList)) {
            for (int i = 0; i < names.size(); i++) {
                sysGroupList.add(GroupDO.builder().name(names.get(i)).info(infos.get(i)).
                        level(EnumUtils.valueOf(GroupLevelEnum.class, levels.get(i))).build());
            }
            groupService.saveBatch(sysGroupList);
            return;
        }

        List<String> insertNames = defaultGroupList.stream().map(GroupDO::getName).filter(
                odlName -> !names.contains(odlName)
        ).collect(Collectors.toList());

        if (CollUtil.isEmpty(insertNames)) {
            return;
        }

        insertNames.stream().forEach(
                n -> {
                    int index = 0;
                    for (int i = 0; i < names.size(); i++) {
                        if (n.equals(names.get(i))) {
                            index = i;
                            break;
                        }
                    }
                    GroupDO groupDO = new GroupDO();
                    groupDO.builder().name(names.get(index)).info(infos.get(index)).
                            level(EnumUtils.valueOf(GroupLevelEnum.class, levels.get(index))).build();
                    sysGroupList.add(groupDO);
                }
        );
        groupService.saveBatch(sysGroupList);
    }

//    private void createAdminGroupPermission() {
//        QueryWrapper<GroupDO> wrapper = new QueryWrapper<>();
//        wrapper.lambda().in(GroupDO::getName, "admin");
//        GroupDO adminGroup = groupService.getOne(wrapper);
//        QueryWrapper<PermissionDO> permissionWrapper = new QueryWrapper<>();
//        permissionWrapper.lambda().eq(PermissionDO::getModule, "权限管理");
//        List<PermissionDO> adminPermissions = permissionService.getBaseMapper().selectList(permissionWrapper);
//        List<GroupPermissionDO> list = adminPermissions.stream().map(p -> new GroupPermissionDO(adminGroup.getId(), p.getId())).collect(Collectors.toList());
//        groupPermissionService.saveOrUpdateBatch(list);
//    }

}
